package org.lalib.controller.action;

import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.lalib.acquire.IControllerAction;
import org.lalib.controller.form.CFoodForm;
import org.lalib.controller.service.CFoodService;
import org.lalib.entity.object.EFood;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("request")
@Controller("cFoodAction")
public class CFoodAction implements IControllerAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	CFoodForm cFoodForm;

	@Autowired
	CFoodService cFoodService;

	public String init() {
		cFoodForm.setFoods(getAllFoods());
		return "foodDefination";
	}

	public void save() {
		String name = cFoodForm.getName();
		Date since = cFoodForm.getSince();
		Date till = cFoodForm.getTill();
		EFood food = new EFood();
		food.setName(name);
		food.setSince(since);
		food.setTill(till);
		cFoodService.save(food);
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Kaydedildi.", ""));
		cFoodForm.clear();
		cFoodForm.setFoods(getAllFoods());
	}
	
	public void delete(EFood food){
		food = (EFood) cFoodService.getFoodById(food.getId());
		cFoodService.delete(food);
		cFoodForm.setFoods(getAllFoods());
	}
	
	private List<EFood> getAllFoods(){
		return cFoodService.getAllFoods();
	}
}